package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.core.domain.QRCodeRecord;
import com.ruitaowang.core.domain.SysUser;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.QRCodeRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class APIQrcode extends BaseController {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Autowired
    private QRCodeRecordService qRCodeRecordService;

    @RequestMapping("/api/admin/Qrcode")
    public String qrcodeList(QRCodeRecord qrCodeRecord){
        MsgOut o = MsgOut.success(qRCodeRecordService.select(qrCodeRecord));
        return this.renderJson(o);
    }

    @RequestMapping("/api/admin/Qrcode/page")
    public String adminQrcode(QRCodeRecord qrCodeRecord,int page){
        qrCodeRecord.setPage(page);
        if (!ObjectUtils.isEmpty(qrCodeRecord.getSidx())){
            qrCodeRecord.setOrderBy(qrCodeRecord.getSidx() + " " + qrCodeRecord.getSord() + ","+ qrCodeRecord.getOrderBy());
        }
        MsgOut o = MsgOut.success(qRCodeRecordService.selectForPage(qrCodeRecord));
        o.setRecords(qrCodeRecord.getRecords());
        o.setTotal(qrCodeRecord.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value ="/api/admin/Qrcode/cellEdit", method = RequestMethod.POST)
    public String adminUpdate(Long id,Byte buyStatus){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        QRCodeRecord qrCodeRecord = new QRCodeRecord();
        qrCodeRecord.setUserId(id);
        qrCodeRecord.setBuyStatus(buyStatus);
        List<QRCodeRecord> qrCodeRecords = qRCodeRecordService.selectForUserId(id);
        if (!ObjectUtils.isEmpty(qrCodeRecords)){
            Long ids = qrCodeRecords.get(0).getId();
            qrCodeRecord.setId(ids);
            qRCodeRecordService.update(qrCodeRecord);
        }else{
            qRCodeRecordService.insert(qrCodeRecord);
        }
        MsgOut o = MsgOut.success(qrCodeRecord);
        return this.renderJson(o);
    }

}
